package com.example.webMagic;

import com.example.domain.Dish;
import com.example.domain.Menu;
import com.example.mapper.DishMapper;
import com.example.mapper.MenuMapper;
import com.example.service.MenuService;
import com.example.utils.GenerateUUID;
import com.example.utils.SnowflakeIdGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import javax.annotation.Resource;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.List;

import static java.awt.SystemColor.menu;

//页面解析类
@Component
public class JobProsser implements PageProcessor {

    private static String url = "http://www.gli.com.cn/l/2-2-285.html";

    private String User_Agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0";
    private String Referer = "http://www.gli.com.cn/l/2-2-285.html";
    private String Cookie = "ASPSESSIONIDACCSSTBC=HMABPAJCFIFIADJLALNNICOC; ASPSESSIONIDSSATAADQ=BHLFLJDDEHMGJEALKPIIDMEF; ASPSESSIONIDQATQTCQS=KGOLGCODKIJKOBPEFHENGGOF";
    private Site site = Site.me()
            //设置编码
            .setCharset("utf8")
            //设置超时时间
            .setTimeOut(10*1000)
            //重试次数
            .setRetryTimes(3)
            //重试时间
            .setRetrySleepTime(3*1000)
            //请求头信息
            .addHeader("User-Agent", User_Agent)
            .addHeader("Referer", Referer)
            .addHeader("Cookie", Cookie);  // 添加有效的 Cookie;

    @Override
    public Site getSite() {
        //使用设置
        return site;
    }

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private DishMapper dishMapper;

    private String downloadDir = "D:\\ideaWorkSpace\\spider\\src\\main\\resources\\dish\\";

//    private String menuId = null;
    //页面解析函数
    @Override
    public void process(Page page) {

        Html html = page.getHtml();
        List<Selectable> nodes = html.css("ul#zuixinliulan_shu td").nodes();
        int menu_num = menuMapper.selectAll();

        if (nodes != null && nodes.size()!=0 && menu_num == 0) {
            //获取存储分类信息
            getCategoryList(page);
        } else if (nodes != null && nodes.size()!=0 && menu_num != 0) {
            //获取蛋糕详细信息
            getCakeList(page);
        } else{
            //添加蛋糕
            addCake(page);
        }

    }

    public void getCategoryList(Page page){
        Html html = page.getHtml();
        List<Selectable> nodes = html.css("ul#zuixinliulan_shu td").nodes();
        for (Selectable node : nodes) {
            String link = node.links().get();
            //判断是否含有链接
            if (link != null && !link.isEmpty()) {
                //获取导航信息
                String menu_node = node.toString();
                String menu = Jsoup.parse(menu_node).text();
                String menuId = GenerateUUID.getId();
                Long id = SnowflakeIdGenerator.getId();
                //查询数据
                Menu me = menuMapper.selectByMenu(menu);
                if (me == null) {
                    //生成对象
                    Menu m = new Menu();
                    m.setId(id);
                    m.setMenuId(menuId);
                    m.setMenu(menu);
                    m.setCanteenId("001");
                    //保存数据
                    menuMapper.insert(m);
                    //换页
                    Request request = new Request(link);
                    //添加参数
                    request.putExtra("menuId",menuId);
                    //发送请求
                    page.addTargetRequest(request);
                }
            }
        }

    }
    public void getCakeList(Page page){
        Html html = page.getHtml();
        //获取蛋糕分类
        String menuId = page.getRequest().getExtra("menuId").toString();
        //获取蛋糕页面链接
        List<String> links = html.css("div#JS_goods_list").links().all();
        //获取蛋糕详细页面
        for (String l : links) {
            //创建请求
            Request request = new Request(l);
            System.err.println("蛋糕详细页面："+l);
            //添加参数
            request.putExtra("menuId", menuId);
            //加入计划
            page.addTargetRequest(request);
        }
    }
    public void addCake(Page page){
        Html html = page.getHtml();
        //获取蛋糕分类
        String menuId = page.getRequest().getExtra("menuId").toString();
        //获取数据
        String name = Jsoup.parse(html.css("div#J_ItemDesc > div >table").nodes().get(0).css("td").nodes().get(1).toString()).text().replace("名称：", "");
        if (dishMapper.selectByName(name) != null) {
            System.err.println("该蛋糕已包含....");
            return;
        };
        int price = Integer.parseInt(html.css("strong#mem_price", "text").toString().replace("¥", ""));
        String description = Jsoup.parse(html.css("div#J_ItemDesc > div >table").nodes().get(0).css("td").nodes().get(7).toString()).text();
        String imageUrl = html.css("img#J_ImgBooth", "src").toString();
        String imageName = downloadImage(imageUrl, downloadDir);
        Long id = SnowflakeIdGenerator.getId();
        //生成对象
        Dish dish = new Dish();
        dish.setId(id);
        dish.setDishId(GenerateUUID.getId());
        dish.setPrice(BigDecimal.valueOf(price));
        dish.setName(name);
        dish.setGrade(BigDecimal.valueOf(10.0));
        dish.setMenuId(menuId);
        dish.setDescription(description);
        dish.setAvatar(imageName);
        dish.setCanteenId("001");
        dish.setTagId("2");
        //保存数据
        dishMapper.insert(dish);
    }

    //判断是否为json格式
    public boolean isValidJson(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.readTree(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //下载图片
    public String downloadImage(String imageUrl, String downloadDir) {
        //提取后缀
        String suffix = imageUrl.substring(imageUrl.lastIndexOf("."));
        //重命名
        String fileName = GenerateUUID.getId()+suffix;
        //下载路径
        String path = downloadDir + fileName;
        //下载图片
        try {
            FileUtils.copyURLToFile(new URL(imageUrl), new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }



}
